<!-- 船代操作分配 -->
<template>
  <div class="ship-generation-distribution">
    <!-- 查询 -->
    <el-form label-width="80px" :model="formData" size="mini" :inline="true" class="demo-form-inline">
      <el-row :gutter="15">
        <el-col :span="16">
          &nbsp;
        </el-col>
        <el-col :span="8">
          <div style="display: flex; justify-content: flex-end; height: 29px; margin-bottom: 20px;">
            <el-form-item>
              <el-input v-model="formData.searchMent" clearable @keyup.enter.native="searchBoxagReementmain()"></el-input>
            </el-form-item>
            <el-button type="primary" size="mini" @click="searchBoxagReementmain()">搜索</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.5)"
      border @cell-click="setmySales" :cell-style="tableRowClass" :data="tableData" style="width: 100%">

      <el-table-column
        align="center"
        label="船代名">
        <template slot-scope="scope">
          {{scope.row.text}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="260px"
        label="操作员">
        <template slot-scope="scope">
          {{scope.row.salesName || '默认操作员'}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="放箱员">
        <template slot-scope="scope">
          {{scope.row.boxName || '默认放箱员'}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="放箱协议">
        <template slot-scope="scope">
          {{scope.row.putBoxCompany || '无'}}
        </template>
      </el-table-column>
      <!-- <el-table-column
        align="center"
        label="转单放箱公司">
        <template slot-scope="scope">
          {{scope.row.protocolCode}}
        </template>
      </el-table-column> -->
    </el-table>
    <el-popover placement="top" ref="operationPopover" width="300" v-model="showPopover">
      <el-select size="mini" v-if="popoverType === 1" filterable @visible-change="selectMan" v-model="salesMan" placeholder="请选择操作员">
        <el-option v-for="item in salesmanList" :key="item.id" :label="item.fullName" :value="item.salesmanId"></el-option>
      </el-select>
      <el-select size="mini" v-if="popoverType === 2" filterable @visible-change="selectBoxMan" v-model="boxMan" placeholder="请选择放箱员">
        <el-option v-for="item in boxerList" :key="item.id" :label="item.fullName" :value="item.salesmanId"></el-option>
      </el-select>
      <el-select size="mini" v-if="popoverType === 3" filterable @visible-change="selectBoxag" allow-create default-first-option multiple v-model="fffff" placeholder="请选择放箱公司">
        <el-option v-for="item in boxagReementmain" :key="item.id" :label="item.text" :value="item.protocolCode"></el-option>
      </el-select>
      <div style="text-align: right; margin: 0; display: inline-block;">
        <el-button size="mini" type="primary" icon="el-icon-check" @click="setShipGeneration()"></el-button>
        <el-button size="mini" icon="el-icon-close" @click="closePopoverHandler"></el-button>
      </div>
    </el-popover>
  </div>
</template>

<script>
import {
  getShipAgencyList,
  setShipAgency,
  agreementList
} from './api/revocationSummary'
import {
  getSalesman
} from '../userMan/api/userman.js'
export default {
  data () {
    return {
      showPopover: false, // 是否显示popover
      cacheId: '', // 缓存船公司ID
      cacheColumnLabel: '', // 缓存表哥文本
      tableData: [],
      formData: {
        searchMent: ''
      },
      popoverType: 0,
      rowData: {},
      fffff: [], // 放箱公司
      boxMan: '', // 放箱员
      salesMan: '', // 业务员员
      boxagReementmain: [], // 放箱协议列表
      salesmanList: [], // 业务员员列表
      boxerList: [], // 放箱员列表
      marr2: [],
      loading: true
    }
  },
  mounted () {
    this.getShipGeneration()
    this.getBoxagReementmain()
    this.getSalesmanList()
    this.getBoxerList()
  },
  methods: {
    // 获取船代列表
    async getShipGeneration () {
      this.loading = true
      const res = await getShipAgencyList({})
      this.marr2 = []
      if (res.status === 200) {
        this.tableData = res.data
        this.tableData.forEach(flg => {
          if (this.boxagReementmain.length !== 0 && flg.protocolCode) {
            let vae = flg.protocolCode.split(',')
            this.marr2 = []
            vae.map(abc => {
              const findIndex = this.boxagReementmain.findIndex((item) => {
                return item.protocolCode === abc
              })
              if (findIndex > -1) {
                this.marr2.push(this.boxagReementmain[findIndex].text)
                flg.putBoxCompany = this.marr2.toString()
              }
            })
          }
          if (this.boxerList.length !== 0) {
            const findIndex1 = this.boxerList.findIndex((item) => {
              return item.salesmanId === flg.putBoxManId
            })
            if (findIndex1 > -1) {
              flg.boxName = this.boxerList[findIndex1].fullName
            }
          }
          if (this.salesmanList.length !== 0) {
            const findIndex2 = this.salesmanList.findIndex((item) => {
              return item.salesmanId === flg.operatorId
            })
            if (findIndex2 > -1) {
              flg.salesName = this.salesmanList[findIndex2].fullName
            }
          }
        })
        this.loading = false
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
        this.loading = false
      }
    },
    // 点击弹窗
    setmySales (row, column, cell, event) {
      let path = event.path || (event.composedPath && event.composedPath())
      // console.log(path,' fffff')
      const target = path[1]
      if (column.label === '操作员') {
        this.popoverType = 1
        this.rowData = row
        this.showPopoverHandler(target, row.id, column.label)
        this.salesMan = row.operatorId
      } else if (column.label === '放箱员') {
        this.popoverType = 2
        this.boxMan = row.putBoxManId
        this.rowData = row
        this.showPopoverHandler(target, row.id, column.label)
      } else if (column.label === '放箱协议') {
        this.popoverType = 3
        this.fffff = row.protocolCode ? row.protocolCode.split(',') : []
        this.rowData = row
        console.log(typeof this.fffff, 'selse')
        this.showPopoverHandler(target, row.id, column.label)
      }
    },
    closePopoverHandler () {
      this.cacheId = ''
      this.cacheColumnLabel = ''
      this.salesMan = ''
      this.boxMan = ''
      this.fffff = []
      this.showPopover = false
      this.$refs.operationPopover.$refs.popper.removeAttribute('style')
    },
    // 绑定显示popover方法
    showPopoverHandler (element, id, label) {
      // 显示、隐藏条件
      if (this.cacheId === id && this.cacheColumnLabel === label) {
        this.showPopover = !this.showPopover
        return
      } else {
        this.cacheId = id
        this.cacheColumnLabel = label
        this.showPopover = true
      }
      // 设置popover样式
      const popper = this.$refs.operationPopover.$refs.popper
      if (this.showPopover) {
        setTimeout(() => {
          const { left, top } = this.getPopoverPosition(element)
          const offset = 100
          const offsetL = 20
          console.log(element.clientWidth, left)
          popper.setAttribute('style', `position: absolute; width: 318px; top: ${top + offset}px; left: ${left - offsetL}px;`)
        }, 100) // 100ms延迟,等待dom渲染
      } else {
        popper.removeAttribute('style')
      }
    },
    // 获取popover距离顶部、左侧的位置
    getPopoverPosition (element) {
      let top = element.offsetTop
      let left = element.offsetLeft
      // let current = element.offsetParent
      // while (current !== null) {
      //   top += current.offsetTop
      //   left += current.offsetLeft
      //   current = current.offsetParent
      // }
      return { top, left }
    },
    // 设置操作员 业务员 方箱协议
    async setShipGeneration () {
      if (this.fffff.length !== 0) {
        this.fffff = this.fffff.join(',')
      } else {
        this.fffff = ''
      }
      let fi = this.fffff !== '' ? this.fffff : this.rowData.protocolCode
      let box = this.boxMan !== '' ? this.boxMan : this.rowData.putBoxManId
      let sales = this.salesMan !== '' ? this.salesMan : this.rowData.operatorId
      const res = await setShipAgency({
        operatorId: sales,
        putBoxManId: box,
        protocolCode: fi,
        shipAgencyId: this.rowData.shipAgencyId
      })
      if (res.status === 200) {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success'
        })
        this.closePopoverHandler()
        this.salesMan = ''
        this.boxMan = ''
        this.fffff = []
        this.getShipGeneration()
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 获取放箱协议
    async getBoxagReementmain () {
      const res = await agreementList({})
      if (res.status === 200) {
        this.boxagReementmain = res.data
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 获取放箱员列表
    async getBoxerList () {
      const res = await getSalesman({
        nickName: '',
        state: 1,
        userType: 9,
        page: 1,
        num: 10000
      })
      if (res.status === 200) {
        this.boxerList = res.data
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 获取业务员列表
    async getSalesmanList () {
      const res = await getSalesman({
        nickName: '',
        state: 1,
        userType: 8,
        page: 1,
        num: 10000
      })
      if (res.status === 200) {
        this.salesmanList = res.data
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 关闭
    // cancelInput (id) {
    //   this.$refs[id].doClose()
    // },
    tableRowClass ({row, column, rowIndex, columnIndex}) {
      if (column.label === '放箱协议' || column.label === '放箱员' || column.label === '操作员') {
        return 'color: #3c8dbc'
      }
    },
    // 搜索
    searchBoxagReementmain () {
      let search = this.formData.searchMent.toLowerCase()
      let arr = []
      if (search === '') {
        this.getShipGeneration()
        return false
      }
      this.tableData.map((item, index) => {
        for (let key in item) {
          if (item[key].toLowerCase().indexOf(search) !== -1) {
            arr.push(item)
          }
        }
      })
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] === arr[j]) {
            arr.splice(j, 1)
            j--
          }
        }
      }
      this.tableData = arr
    },
    selectMan (value) {
      let _that = this
      if (value) {
        setTimeout(function () {
          _that.getSalesmanList()
        }, 500)
      }
    },
    selectBoxMan (value) {
      let _that = this
      if (value) {
        setTimeout(function () {
          _that.getBoxerList()
        }, 500)
      }
    },
    selectBoxag (value) {
      let _that = this
      if (value) {
        setTimeout(function () {
          _that.getBoxagReementmain()
        }, 500)
      }
    }
  }
}
</script>

<style lang="less">
.ship-generation-distribution {}
</style>
